package com.ccc3gc.servlet;

import com.ccc3gc.dao.UserDao;
import com.ccc3gc.dao.impl.UserDaoImpl;
import com.ccc3gc.entity.User;
import com.ccc3gc.util.UpUtils;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/changeUser")
public class ChangeUserServlet extends HttpServlet {
    UserDao userDao = new UserDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SmartUpload smartUpload = UpUtils.getSmartUpload(getServletConfig(), req, resp);
        String fileName = smartUpload.getFiles().getFile(0).getFileName();
        Request request = smartUpload.getRequest();
        String username = request.getParameter("username");
        int userId = Integer.parseInt(request.getParameter("userId"));
        User user = new User(userId, username, fileName);
        if (userDao.updateUser(user) > 0) {
            resp.sendRedirect("userPage");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        int userId = Integer.parseInt(req.getParameter("userId"));
        User user = userDao.selectUserById(userId);
        req.setAttribute("user", user);
        req.getRequestDispatcher("changeUser.jsp").forward(req, resp);
    }
}
